package com.lance.answer.gui.answer.gk.answer.lms.util;

import com.alibaba.fastjson.JSON;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ImageUtil {

    public static void main(String[] args) {

        String urlTask = "https://lms.ouchn.cn/exam/20000023615/subjects#/submission/20000069283";

        System.err.println(urlTask.substring(urlTask.indexOf("/exam/")+6));
        long examId = Long.parseLong(urlTask.substring(urlTask.indexOf("/exam/") + 6, urlTask.indexOf("/subjects")));
        long submissionId = Long.parseLong(urlTask.substring(urlTask.indexOf("/submission/") + 12));
        System.err.println("examId："+examId);
        System.err.println("submissionId："+submissionId);


        String s = "，，|[http://oss.ouchn.cn/zongbu/jiaoyu/%E5%B7%A5%E7%A8%8B%E6%95%B0%E5%AD%A6%EF%BC%88%E6%9C%AC%EF%BC%89/xingkao2/21102.png, http://oss.ouchn.cn/zongbu/jiaoyu/%E5%B7%A5%E7%A8%8B%E6%95%B0%E5%AD%A6%EF%BC%88%E6%9C%AC%EF%BC%89/xingkao2/21103.png, http://oss.ouchn.cn/zongbu/jiaoyu/%E5%B7%A5%E7%A8%8B%E6%95%B0%E5%AD%A6%EF%BC%88%E6%9C%AC%EF%BC%89/xingkao2/21104.png]";
        s = s.substring(s.indexOf("|[")+2,s.length()-1);
     //   s = s.substring(0,s.indexOf("|[")+2);
        System.err.println("s:"+s);
        System.err.println(s.split(",").length);

        System.err.println(JSON.toJSONString(getImageFromNetByUrl("http://oss.ouchn.cn/zongbu/jiaoyu/%E5%B7%A5%E7%A8%8B%E6%95%B0%E5%AD%A6%EF%BC%88%E6%9C%AC%EF%BC%89/xingkao1/11195.png")));
        System.err.println(JSON.toJSONString(getImageFromNetByUrl("https://lms.ouchn.cn/api/uploads/20000164500/in-rich-content?created_at=1649408317")));
    }

    // 以前国开的链接图片可能会失效。。。。。。。。。。考虑是否都要替换一下。。。。
    public static byte[] getImageFromNetByUrl(String strUrl){
        try {
            URL url = new URL(strUrl);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(3 * 1000);
            InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
            byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
            return btImg;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 从输入流中获取数据
     * @param inStream 输入流
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len=inStream.read(buffer)) != -1 ){
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

}
